package com.kstech.mp3604.base


object FaultNameData {
    val dj_arr = arrayOf(
        "电源欠压(PwrLow)",
        "电机位置异常(PosErr)",
        "电机霍尔错误(反馈异常) (HallErr)",
        "电机过流(CurOvr)",
        "电机超载(DrvOvr)",
        "EEPROM故障(EromErr)",
        "电机IGBT故障(IGBTErr)",
        "驱动器过热(DrvHot)",
        "电机电机缺相(MotErr)",
        "电机电流超差(CurErr)",
        "电机速度超差(SpdErr)",
        "电机电机过热(MotHot)",
        "电源过压(PwrHig)",
        "ABS通讯故障",
        "抱闸错误",
        "锁定"
    )

    fun get(data1: Int, data2: String): String {
        return when (data1) {
            1 -> {
                "电机1故障码-${addDJFault(data2)}"
            }

            2 -> {
                "电机2故障码-${addDJFault(data2)}"
            }

            3 -> {
                "电机3故障码-${addDJFault(data2)}"
            }

            4 -> {
                "电机4故障码-${addDJFault(data2)}"
            }

            5 -> {
                "吊装系统故障码"
            }

            6 -> {
                when (data2) {
                    "0100" -> {
                        "控制器系统故障码-前拉绳故障"
                    }

                    "0200" -> {
                        "控制器系统故障码-后拉绳故障"
                    }

                    "0300" -> {
                        "控制器系统故障码-前激光测距故障"
                    }

                    "0400" -> {
                        "控制器系统故障码-前激光测距故障"
                    }

//                    "0500" -> {
//                        "控制器系统故障码-码放位置出现异常"
//                    }

                    else -> {
                        "数据格式未定义：faultIndex:$data1,faultCode:$data2"
                    }
                }
            }
            7->{
                "吊装横移伺服故障码"
            }
            8->{
                "吊装卷扬伺服故障码"
            }

            else -> {
                "数据格式未定义：faultIndex-$data1,faultCode-$data2"
            }
        }
    }

    /**
     * 添加电机
     * 低位在前
     */
    private fun addDJFault(hexData: String): String {
        val stringBuffer = StringBuffer()
        // 提取 8 位二进制数组（低位在前）
        val value = hexData.chunked(2).reversed().joinToString("").toUShort(16)

        // 2. 转为16位二进制字符串（补零到16位）
        val binaryStr = value.toString(2).padStart(16, '0')

        val result = binaryStr.reversed()
        result.forEachIndexed { index, value ->
            if (value == '1') {
                stringBuffer.append("${dj_arr[index]} ")
            }
        }
        return stringBuffer.toString()
    }

}